import os
from jieba.analyse import ChineseAnalyzer
import jieba
import logging
from whoosh.qparser import MultifieldParser
from services import Singleton
from logic.articleDao import articleDao
from whoosh.index import create_in
from whoosh.fields import Schema,ID,TEXT
jieba.setLogLevel(logging.ERROR)
ana=ChineseAnalyzer()

class Search(metaclass=Singleton):
    def __init__(self):
        self.list = articleDao().listAllNoPage()
        schema = Schema(
            id=ID(stored=True, analyzer=ana),
            title=TEXT(stored=True, analyzer=ana),
            content=TEXT(stored=True, analyzer=ana),
            keyword=TEXT(stored=True, analyzer=ana),
            desc=TEXT(stored=True, analyzer=ana),)
        if not os.path.exists("index"):
            os.mkdir("index")
        ix= create_in("index",schema)
        writer = ix.writer()
        for art in self.list:
            writer.add_document(
                            id=str(art.id),
                           title=art.title,
                           content=art.content,
                           keyword=art.keyword,
                           desc=art.desc)
        writer.commit()
        self.ix= ix

    def search(self,keyword):
        searcher = self.ix.searcher()
        query = MultifieldParser(["content","title","desc","keyword"],schema=self.ix.schema).parse(keyword)
        res=searcher.search(query,limit=len(self.list))
        result = []
        for r in res:
            result.append(r.get("id"))
        searcher.close()
        del res
        return result

    @classmethod
    def clear(cls):
        cls._instances = {}